package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import domian.PageBean;
import domian.Result;
import domian.User;
import redis.clients.jedis.Jedis;
import service.impl.ConcernServiceImpl;
import service.impl.ReviewServiceImpl;
import utils.Redis;
import utils.ToolSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;

/**
 * 关注serclet
 */
@WebServlet("/concern/*")
public class ConcernServlet extends BaseServlet{
    ConcernServiceImpl concernService = new ConcernServiceImpl();
    /**
     * 点击关注获得文件的id - 从文件的id找到当前用户的id
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void fileId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求
        String href = req.getParameter("href"); //地址
        String concern = req.getParameter("concern"); //关注状态

        /*System.out.println(href+"---"+concern );*/

        //截取地址里的文件的id
        String id = null;
        try {
            URL urlObj = new URL(href);
            String query = urlObj.getQuery();
            String[] params = query.split("&");

            for (String param : params) {
                String[] keyValue = param.split("=");
                String key = URLDecoder.decode(keyValue[0], "UTF-8");
                String value = URLDecoder.decode(keyValue[1], "UTF-8");

                if (key.equals("id")) {
                    id = value;
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Integer fid = Integer.parseInt(id); //文件id
        //从redis获取当前用户
        Jedis jedis = new Jedis();
        //获取用户客户端标识
        String redisKey = Redis.getRedisKey(req);
        String json = jedis.get(redisKey);
        ObjectMapper om = new ObjectMapper();
        User users = om.readValue(json, User.class);
        Integer uid = users.getUid(); //登录用户id
        String nickname = users.getNickname(); //登录用户昵称
        //前段传入关注信息、登录用户的id以及该文件的id
        concernService.concernMessage(uid,concern,fid,nickname); //将信息传入service,进行关注、取消关注判断
    }

    /**
     * 取消关注
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void userId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Integer uid = Integer.parseInt(req.getParameter("uid"));  //当前登录用户id
        Integer userId = Integer.parseInt(req.getParameter("userId"));  //被关注的用户id
        String concern = req.getParameter("concern");   //关注信息

        //获取用户客户端标识
        String redisKey = Redis.getRedisKey(req);
        //从redis获取当前用户
        Integer uid = uId(redisKey);

        concernService.concernUid(uid,userId,concern);



    }

    /**
     * 从数据库查询的信息传到前端
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void aInformation(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求
        //Integer uid = Integer.parseInt(req.getParameter("uid"));
        Integer pages = Integer.valueOf(req.getParameter("pages")); //第几页

        //获取用户客户端标识
        String redisKey = Redis.getRedisKey(req);
        //从redis获取当前用户
        Integer uid = uId(redisKey);

        //将用户关注用户的信息以及粉丝数量信息传入前段
        PageBean pageBean = concernService.queryConcern(uid,pages,redisKey);
        //响应结果
        ToolSet.printWriter(resp,pageBean);
    }

    /**
     * 登录用户查看关注用户的上传的资源
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void userMessage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求
        String href = req.getParameter("href");  //拿到地址 从地址中获取当前关注用户的id
        Integer pageNum = Integer.parseInt(req.getParameter("pageNum")); //页数
        /*System.out.println("gucaj   "+href);
        System.out.println(pageNum);*/

        //截取地址里的文件的id
        String id = null;
        try {
            URL urlObj = new URL(href);
            String query = urlObj.getQuery();
            String[] params = query.split("&");

            for (String param : params) {
                String[] keyValue = param.split("=");
                String key = URLDecoder.decode(keyValue[0], "UTF-8");
                String value = URLDecoder.decode(keyValue[1], "UTF-8");

                if (key.equals("id")) {
                    id = value;
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Integer uid = Integer.parseInt(id); //被关注用户id

        //从redis拿到当前用户的对象
        /*ObjectMapper om = new ObjectMapper();
        User json = om.readValue("json", User.class);
        System.out.println("当前登录用户信息： "+json);*/

        PageBean pageBean = concernService.attentionData(uid, pageNum);
        //响应结果
        ToolSet.printWriter(resp,pageBean);
    }

    /**
     * 控制关注按钮 （有关注显示已经关注，没有关注显示关注）
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void followFid (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户客户端标识
        String redisKey = Redis.getRedisKey(req);
        //从redis获取当前用户
        Integer uid = uId(redisKey);

       PageBean pageBean = concernService.followService(uid);
        //响应结果
       ToolSet.printWriter(resp,pageBean);

    }

    /**
     * 根据当前文件id 查找该文件的用户id
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void followUid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer parameter = Integer.parseInt(req.getParameter("number"));
        ReviewServiceImpl reviewService = new ReviewServiceImpl();
        Result result = reviewService.dataFileContent(parameter);
        //响应结果
        ToolSet.printWriter(resp,result);


    }

    /**
     * 将当前登录用户信息从redis中查到并返回
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void uidMessage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从redis获取当前用户  将当前用户传到前端
        Jedis jedis = new Jedis();
        //获取用户客户端标识
        String redisKey = Redis.getRedisKey(req);
        String json = jedis.get(redisKey);
        ObjectMapper om = new ObjectMapper();
        User user = null;
        if (json != null) {
            user = om.readValue(json, User.class);
        }
        //响应结果
        ToolSet.printWriter(resp,user);
    }

    /**
     * 当前文件的用户信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void documentUserMessage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //请求响应 拿到文件id
        Integer parameter = Integer.parseInt(req.getParameter("number"));

        //调用service方法
        PageBean pageBean = concernService.documentUserMessageService(parameter);
        //响应结果
        ToolSet.printWriter(resp,pageBean);
    }
    //封装从redis调用当前登录用户的id方法
    public static Integer uId(String user) throws IOException {
        Jedis jedis = new Jedis();
        String json = jedis.get(user);
        ObjectMapper om = new ObjectMapper();
        User users = om.readValue(json, User.class);
        Integer uid = users.getUid();
        return  uid;
    }

}
